# -*- coding: utf-8 -*-

import yaml
from typing import Any, Optional

class ConfigManager:
    def __init__(self, file_path = "config.yaml"):
        """
        初始化 YAML 配置文件管理类
        :param file_path: YAML 配置文件的路径
        """
        self.file_path = file_path
        self.config = self._load_config()

    def _load_config(self) -> dict:
        """
        加载 YAML 配置文件
        :return: 配置字典
        """
        try:
            with open(self.file_path, "r", encoding="utf-8") as file:
                return yaml.safe_load(file) or {}
        except FileNotFoundError:
            return {}

    def _save_config(self):
        """
        保存配置到 YAML 文件
        """
        with open(self.file_path, "w", encoding="utf-8") as file:
            yaml.safe_dump(self.config, file, default_flow_style=False, allow_unicode=True)

    def get(self, key: str, default: Optional[Any] = None) -> Any:
        """
        获取配置项的值
        :param key: 配置项的路径（用点号分隔，如 "app.settings.debug"）
        :param default: 如果配置项不存在，返回的默认值
        :return: 配置项的值
        """
        keys = key.split(".")
        value = self.config
        for k in keys:
            if isinstance(value, dict) and k in value:
                value = value[k]
            else:
                return default
        return value

    def set(self, key: str, value: Any):
        """
        设置配置项的值
        :param key: 配置项的路径（用点号分隔，如 "app.settings.debug"）
        :param value: 要设置的值
        """
        keys = key.split(".")
        current = self.config
        for k in keys[:-1]:
            if k not in current or not isinstance(current[k], dict):
                current[k] = {}
            current = current[k]
        current[keys[-1]] = value
        self._save_config()

    def delete(self, key: str):
        """
        删除配置项
        :param key: 配置项的路径（用点号分隔，如 "app.settings.debug"）
        """
        keys = key.split(".")
        current = self.config
        for k in keys[:-1]:
            if k not in current or not isinstance(current[k], dict):
                return
            current = current[k]
        if keys[-1] in current:
            del current[keys[-1]]
            self._save_config()

    def __str__(self):
        """
        返回配置的字符串表示
        """
        return yaml.safe_dump(self.config, default_flow_style=False, allow_unicode=True)




if __name__ == "__main__":

    # 用法示例
    path = "../config.yaml"
    config_manager = ConfigManager(file_path = path)
    config = config_manager.get("database.path")
    print(config)
    config_manager.set("database.newpath", "../12/32")
    config_manager.set("test.app", "test")
    print(config_manager)
    config_manager.delete("database.newpath")
    print(config_manager)
    config_manager.delete("test.app")
    print(config_manager)
    config_manager.delete("test")